import gi, time
gi.require_version("Gtk", "4.0")
from gi.repository import Gtk, Gio, GLib

class DBusService(Gio.DBusInterfaceSkeleton):
    __gtype_name__ = 'DBusService'

    def __init__(self):
        super().__init__()
        self.connection = None

    def emit_message(self, message):
        # 发送信号到主线程
        self.emit_signal(None, "/com/example/DBusService", "com.example.DBUS", "OnMessage", GLib.Variant("(s)", (message,)))

    @Gio.DBusInterfaceSkeleton.signal_signature("s")
    def OnMessage(self, message):
        print(f"Received message in main thread: {message}")

def worker_function(dbus_service):
    for i in range(5):
        # 模拟子线程发送消息
        dbus_service.emit_message(f"Message {i}")
        time.sleep(1)

if __name__ == "__main__":
    app = Gtk.Application(application_id="com.example.DBusApp")

    def on_activate(app):
        window = Gtk.ApplicationWindow(application=app)
        window.set_title("DBus Example")
        window.set_default_size(200, 100)
        window.present()

        dbus_service = DBusService()
        connection = Gio.bus_get_sync(Gio.BusType.SESSION, None)
        dbus_service.export(connection, "/com/example/DBusService")

        # 启动子线程
        import threading
        threading.Thread(target=worker_function, args=(dbus_service,), daemon=True).start()

    app.connect("activate", on_activate)
    app.run()